//
//  BloodOxygenChartView.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/8/1.
//

import SwiftUI
import Charts

struct BDataItem : Identifiable{
    let id = UUID()
    let timeRange: String
    let value: Double
}

struct BloodOxygenChartView: View {
    let data: [BDataItem]
    private let maxScore: Double = 100
    
    var body: some View {
            Chart(data) { item in
                PointMark(
                    x: .value("时间", item.timeRange),
                    y: .value("最低值", item.value)
                )
                .symbol(.circle)
                .symbolSize(10)
                .foregroundStyle(Color(hex: "#EF5F5F"))
            }
            .chartXAxis {
                AxisMarks(values: .automatic) { value in
                    AxisGridLine(
                        stroke: StrokeStyle(
                            lineWidth: 0.5,
                            dash: [4, 2])
                    )
                    .foregroundStyle(Color(hex: "#F5F5F5"))
                    if let time = value.as(String.self) {
                        AxisValueLabel {
                            let hour = getHourNumber(date: time)
                            if hour % 6 == 0{
                                Text(time)
                                    .foregroundStyle(Color(hex: "#C1C1C1"))
                                    .font(.system(size: 12))
                                    .frame(width: 100)
                            }
                        }
                    }
                }
            }
            .chartYScale(domain: 0...maxScore)
            .chartYAxis {
                AxisMarks(position: .trailing,values: .stride(by: 20)) { value in
                    if let score = value.as(Double.self) {
                        AxisValueLabel {
                                Text("\(Int(score))")
                                    .foregroundStyle(Color(hex: "#C1C1C1"))
                                    .font(.system(size: 12))
                                    .padding(.leading,10)
                        }
                    }
                }
            }
            .frame(height: 200)
            .chartLegend(.hidden)
        }
    
    func getHourNumber(date:String) -> Int {
        if let colonIndex = date.firstIndex(of: ":") {
            let hourPart = date[..<colonIndex]
            print(String(hourPart))
            return Int(hourPart) ?? 0
        }
        return 0
    }
}

